package com.zhanglifan.service.impl;

import com.zhanglifan.domain.Contract;
import com.zhanglifan.domain.ExtCproduct;
import com.zhanglifan.service.ExtCproductService;
import com.zhanglifan.util.UtilFuns;

import java.io.Serializable;

/**
 * Information
 * Author: ZhangLifan
 * Time: 2017/10/6 8:50
 * Description: ContractServiceImpl
 */
public class ExtCproductServiceImpl extends BaseServiceImpl<ExtCproduct> implements ExtCproductService {

    @Override
    public void saveOrUpdate(ExtCproduct entity) {
        double totle = 0.0;
        Contract contract = (Contract) baseDao.get(Contract.class, entity.getContractProduct().getContract().getId());
        if(UtilFuns.isEmpty(entity.getId())){
            if(UtilFuns.isNotEmpty(entity.getCnumber()) && UtilFuns.isNotEmpty(entity.getPrice())){
                totle = entity.getCnumber() * entity.getPrice();
            }
            entity.setAmount(totle);
            contract.setTotalAmount(contract.getTotalAmount()+totle);
        }else{
            double oldAmount = entity.getAmount()==null ? 0.0 : entity.getAmount();
            if(UtilFuns.isNotEmpty(entity.getCnumber()) && UtilFuns.isNotEmpty(entity.getPrice())){
                totle = entity.getCnumber() * entity.getPrice();
            }
            contract.setTotalAmount(contract.getTotalAmount() - oldAmount + totle);
            entity.setAmount(totle);
        }
        super.saveOrUpdate(entity);
    }


    @Override
    public void deleteById(Class<ExtCproduct> entityClass, Serializable id) {
        ExtCproduct entity = (ExtCproduct) baseDao.get(ExtCproduct.class,id);
        Contract contract = (Contract) baseDao.get(Contract.class, entity.getContractProduct().getContract().getId());
        double amount = entity.getAmount()==null ? 0 : entity.getAmount();
        contract.setTotalAmount(contract.getTotalAmount()-amount);
        super.deleteById(entityClass, id);
    }
}
